package com.guanyong.webapi.controllers.page;

import com.guanyong.model.*;
import com.guanyong.services.*;
import com.guanyong.utils.Comm.ResultCode;
import com.guanyong.utils.Comm.ResultObject;
import com.guanyong.utils.LogHelper.LogHelper;
import com.guanyong.webapi.config.CreateVideoURLUtil;
import com.guanyong.webapi.config.VideoLocalUtil;
import com.guanyong.webapi.handle.GlobleData;
import com.qiniu.common.Zone;

import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Eric.Zhang on 2017/4/12.
 */
@Controller
public class home extends baseController {
    @Autowired
    CommentService commentService;

    @Autowired
    FilmServices filmServices;

    @Autowired
    VideoScoreService videoScoreService;

    @Autowired
    VideoSourceService videoSourceService;

    @Autowired
    CreateVideoURLUtil createVideoURLUtil;


    @Autowired
    GlobleData globleData;


    @Autowired
    MerchantLogService merchantLogService;

    @Autowired
    MerchantService merchantService;


    @RequestMapping({ "/home", "/home/index"})
    String index(HttpServletRequest request) {

        ResultObject<MerchantModel> merchantModelResultObject=
              merchantService.GetMerchantModelByAk("11111");
        MerchantLogModel logModel=new MerchantLogModel();
        logModel.setAk("11111");
        logModel.setIp("1.1.1.1");
        logModel.setServerIp("2.2.2.2");
        logModel.setUserName("mxk");
        logModel.setUrl("www.baidu.com");
        logModel.setObjectId("123123123");
        ResultObject<Integer> resultObject=merchantLogService.addMerchantLog(logModel);


        return "/home/movieIndex";
    }
    @RequestMapping({"/test"})
    String test() throws UnsupportedEncodingException {


        String fileName = "招聘.txt";
        String domainOfBucket =  "ouvhkitm8.bkt.clouddn.com";
        String encodedFileName = URLEncoder.encode(fileName,"utf-8");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

        Auth auth = Auth.create(globleData.Qiniu_SAk, globleData.Qiniu_SSK);
        long expireInSeconds = 3600;//1小时，可以自定义链接过期时间
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);



        return "home/test";
    }



    @RequestMapping({"/welcome"})
    String welcome() {

        return "home/welcome";
    }
    @RequestMapping({"/movieIndex"})
    String movieIndex() {

        return "home/movieIndex";
    }


    @RequestMapping({"/comment"})
    String comment() {

        return "home/comment";
    }
    @RequestMapping({"/myCore"})
    String myCore() {

        return "home/myCore";
    }
    @RequestMapping({"/recommend"})
    String recommend() {

        return "home/recommend";
    }
    @RequestMapping({"/search"})
    String search() {

        return "home/search";
    }

    @RequestMapping({"/details"})
    String details(Model model, HttpServletRequest request) {
        String filmid=request.getParameter("fid");
        FilmModel filmModel=filmServices.GetFilmModelById(filmid);

        model.addAttribute("film",filmModel);
        VideoScoreModel videoScoreModel=videoScoreService.GetVideoScoreByObjectId(1,filmid);
        model.addAttribute("videoscore",videoScoreModel);
        FilmInfoModel filmInfoModel=filmServices.GetFilmInfoModelById(filmid);

        model.addAttribute("filminfo",filmInfoModel);
//        List<VideoSourceModel> sourceModelList=videoSourceService.GetVideoScorceByObjectId(1,
//                filmid,1);
//        model.addAttribute("videosourcelist",sourceModelList);

        VideoSourceModel videoSourceModel=videoSourceService.
                GetVideoScorceByObjectIdType(1,
                        filmModel.getfId(),2);
        if (videoSourceModel!=null){
            Map<String,Object> map = new HashMap<String, Object>();
            String playAuth = null;
            try {
                if (videoSourceModel.getfSourceurl()!=null){
                    playAuth=createVideoURLUtil.getVideoURL(videoSourceModel.getfSourceLocal());
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
            if (playAuth!=null){
                model.addAttribute("videoVoucher",playAuth);
            }else {
                return "errorPage/500";
            }
        }else{
            return "errorPage/500";
        }

        if (filmModel!=null && filmInfoModel!=null&& videoScoreModel!=null&&videoSourceModel!=null){
            return "home/details";
        }
        else{
            return "errorPage/500";
        }
    }
    @RequestMapping({"/videoPlay"})
    String videoPlay(Model model, HttpServletRequest request) {

        String filmid=request.getParameter("fid");
        FilmModel filmModel=filmServices.GetFilmModelById(filmid);

        model.addAttribute("film",filmModel);
        VideoScoreModel videoScoreModel=videoScoreService.GetVideoScoreByObjectId(1,filmid);
        model.addAttribute("videoscore",videoScoreModel);
        FilmInfoModel filmInfoModel=filmServices.GetFilmInfoModelById(filmid);

        model.addAttribute("filminfo",filmInfoModel);
        //本地播放
        VideoSourceModel videoSourceModel=videoSourceService.
                GetVideoScorceByObjectIdType(1,
                        filmModel.getfId(),0);
        if (videoSourceModel!=null){
            Map<String,Object> map = new HashMap<String, Object>();
            String playAuth = null;
            try {
                if (videoSourceModel.getfSourceurl()!=null){
                    playAuth=createVideoURLUtil.getVideoURL(videoSourceModel.getfSourceLocal());
                }
            } catch (Exception e) {
                e.printStackTrace();

            }
            if (playAuth!=null){
                model.addAttribute("videoVoucher",playAuth);
            }else {
                return "errorPage/500";
            }
        }else{
            return "errorPage/500";
        }
        if (filmModel!=null && filmInfoModel!=null&& videoScoreModel!=null){
            return "home/videoPlay";
        }
        else{
            return "errorPage/500";
        }

    }

    @RequestMapping({"/typeVideo"})
    String typeVoide() {
        return "home/typeVideo";
    }


    @RequestMapping({"/searchVideo"})
    String searchVoide() {
        return "home/searchVideo";
    }

    @RequestMapping({"/login"})
    String login() {
        return "home/login";
    }

    @RequestMapping({"/register"})
    String register() {
        return "home/register";
    }

    @RequestMapping({"/upPassword"})
    String upPassword() {
        return "home/upPassword";
    }


    @RequestMapping({"/share"})
    String share() {
        return "home/share";
    }

    @RequestMapping({"/shareH5"})
    String shareH5() {
        return "home/shareH5";
    }

    @RequestMapping({"/demo"})
    String demo() {

        return "home/demo";
    }


    @RequestMapping({"/qiniudemo"})
    String qiniudemo(Model model, HttpServletRequest request) {


        String bucket = "voideapp";

        Auth auth = Auth.create(globleData.QiNiu_Ak, globleData.Qiniu_SK);

        String upToken = auth.uploadToken(bucket);

        System.out.println(upToken);

        model.addAttribute("uptoken",upToken);

        return "home/demo/index";
    }

    @RequestMapping({"/qiniufilelist"})
    String qiniuFileList(Model model, HttpServletRequest request) {


        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
        String accessKey = globleData.QiNiu_Ak;
        String secretKey = globleData.Qiniu_SK;
        String bucket = "voideapp";
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
//文件名前缀
        String prefix = "";
//每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
//指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
//列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                System.out.println(item.key);
                System.out.println(item.hash);
                System.out.println(item.fsize);
                System.out.println(item.mimeType);
                System.out.println(item.putTime);
                System.out.println(item.endUser);
            }
        }

        return "home/test";
    }

    @RequestMapping({"/dianying"})
    String dianying() {

        return "home/echarts/dianying";
    }

}
